package com.zjdiepu.www.rest.api.base;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Id;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.core.ParentModel;
import com.zjdiepu.www.base.enums.status.MessageStatus;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.commpent.handler.TokenUserHelper;
import com.zjdiepu.www.ibiz.other.IOtherMessageAppService;
import com.zjdiepu.www.ibiz.other.IOtherNoticeService;
import com.zjdiepu.www.ibiz.zx.IZxCreditQueryService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.other.dto.OtherMessageApp;
import com.zjdiepu.www.model.other.ext.OtherMessageAppExt;
import com.zjdiepu.www.model.other.ext.OtherNoticeExt;
import com.zjdiepu.www.model.other.request.OtherMessageAppResquest;
import com.zjdiepu.www.model.other.response.InboxDetailResponse;
import com.zjdiepu.www.model.other.response.OtherMessageAppResponse;
import com.zjdiepu.www.model.other.response.OtherMessageAppResponseItem;
import com.zjdiepu.www.util.HtmlUtil;

/**      
 * 项目名称：diepu-parent-manage   
 * 类名称：AppNewsController   
 * 类描述：   
 * 创建人：zhangpp
 * 创建时间：2017年5月31日 下午2:17:32   
 * 修改人：zhangpp
 * 修改时间：2017年5月31日 下午2:17:32   
 * 修改备注：   
 * @version V1.0     
 */
@RestController
@RequestMapping(value= "OtherMessageAppController", produces="application/json;charset=UTF-8", method = RequestMethod.POST)
@Api(tags = {"消息警告"}, produces="application/json;charset=UTF-8")
public class OtherMessageAppController extends BaseController{
	@Resource
	protected TokenUserHelper tokenUserHelper;
	@Resource
	private IOtherMessageAppService otherMessageAppService;
	@Resource
	private IOtherNoticeService otherNoticeService;
	@Resource
	private IZxCreditQueryService zxCreditQueryService;
	
	/**
	 * 收件箱概要
	 * @param otherMessageAppResquest
	 * @return
	 */
	@ApiOperation(value = "收件箱概要", response = InboxDetailResponse.class, httpMethod="POST")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
	@RequestMapping("inboxDetail")
	public ApiResponse inboxDetail(@Validated @RequestBody OtherMessageAppResquest otherMessageAppResquest) {
		SysUser currentUser = tokenUserHelper.getUser();
		
		InboxDetailResponse inboxDetailResponse = new InboxDetailResponse();
		
    	OtherMessageAppExt otherMessageAppExt = new OtherMessageAppExt();
    	otherMessageAppExt.setBaseWhere();
    	otherMessageAppExt.setSalesmanId(currentUser.getSalersmanId());
    	otherMessageAppExt.setWhereSql(" AND `STATUS_MSG` IN (" + MessageStatus.WEI_TUI_SONG.getCode() + "," + MessageStatus.YI_TUI_SONG.getCode() + ") AND `MODE_ID` IN ('" + ModeIDType.CSDZS.getCode() 
			+ "','"  + ModeIDType.FKGPS.getCode() + "','"  + ModeIDType.FKZJSH.getCode() 
			+ "','"  + ModeIDType.ZSYS.getCode() + "','"  + ModeIDType.CSDCS.getCode() 
			+ "','"  + ModeIDType.ZSES.getCode() + "','"  + ModeIDType.DSCS.getCode() 
			+ "','"  + ModeIDType.DSFS.getCode() + "','"  + ModeIDType.FKJLSH.getCode() + "')");
    	
        int fkjgNum = otherMessageAppService.countByExt(otherMessageAppExt);
        inboxDetailResponse.setFkjgNum(fkjgNum);
        
        otherMessageAppExt.setWhereSql(" AND `STATUS_MSG` IN (" + MessageStatus.WEI_TUI_SONG.getCode() + "," + MessageStatus.YI_TUI_SONG.getCode() + ") AND `MODE_ID` IN ('" + ModeIDType.ZXCX.getCode() 
    			+ "','"  + ModeIDType.ZXJG.getCode()  + "','"  + ModeIDType.ZXUG.getCode() + "')");
        int zxfkNum = otherMessageAppService.countByExt(otherMessageAppExt);
        inboxDetailResponse.setZxfkNum(zxfkNum);
        
//        otherMessageAppExt.setWhereSql(" AND `STATUS_MSG` IN (" + MessageStatus.WEI_TUI_SONG.getCode() + "," + MessageStatus.YI_TUI_SONG.getCode() + ") AND  `MODE_ID` NOT IN ('" + ModeIDType.CSDZS.getCode() 
//    			+ "','"  + ModeIDType.FKGPS.getCode() + "','"  + ModeIDType.FKZJSH.getCode() 
//    			+ "','"  + ModeIDType.ZSYS.getCode() + "','"  + ModeIDType.ZXCX.getCode() 
//    			+ "','"  + ModeIDType.ZXJG.getCode() + "','"  + ModeIDType.ZXUG.getCode()
//    			+ "','"  + ModeIDType.CSDCS.getCode() + "','"  + ModeIDType.ZSES.getCode() + "','"  + ModeIDType.DSCS.getCode() 
//    			+ "','"  + ModeIDType.DSFS.getCode() + "','"  + ModeIDType.FKJLSH.getCode() + "')");
        
        otherMessageAppExt.setWhereSql(" AND `STATUS_MSG` IN (" + MessageStatus.WEI_TUI_SONG.getCode() + "," + MessageStatus.YI_TUI_SONG.getCode() + ")");
        int ywtzNum = otherMessageAppService.countByExt(otherMessageAppExt);
        inboxDetailResponse.setYwtzNum(ywtzNum);
        
        OtherNoticeExt otherNoticeExt = new OtherNoticeExt();
    	otherNoticeExt.setBaseWhere();
    	//截止今日没有过期
    	otherNoticeExt.setDateValidStart(DateUtil.truncAndAddDays(new Date(), 0));
        int noticeNum = otherNoticeService.countByExt(otherNoticeExt);
        inboxDetailResponse.setNoticeNum(noticeNum);
        
        return ApiResponse.success(inboxDetailResponse);
	}
	
	
	/**
	 * 风控结果收件箱
	 * @param otherMessageAppResquest
	 * @return
	 */
	@ApiOperation(value = "风控结果收件箱", response = OtherMessageAppResponseItem.class, httpMethod="POST")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
	@RequestMapping("listFkfkResult")
	public ApiResponse listFkfkResult(@Validated @RequestBody OtherMessageAppResquest otherMessageAppResquest) {
		SysUser currentUser = tokenUserHelper.getUser();
    	OtherMessageAppExt otherMessageAppExt = new OtherMessageAppExt();
    	otherMessageAppExt.setBaseWhere();
    	otherMessageAppExt.setSalesmanId(currentUser.getSalersmanId());
    	//查询所有，已查看放后面
    	otherMessageAppExt.setOrderSql("(CASE WHEN `STATUS_MSG` != " + MessageStatus.YI_CHA_KAN.getCode() + " THEN 0 ELSE 1 END), `TIME_CREATE` DESC"); //最新
    	otherMessageAppExt.setPage(otherMessageAppResquest.getPage());
    	otherMessageAppExt.setRows(otherMessageAppResquest.getRows());
//    	不获取mode_id 为这些的信息
    	otherMessageAppExt.setWhereSql(" AND `MODE_ID` IN ('" + ModeIDType.CSDZS.getCode() 
			+ "','"  + ModeIDType.FKGPS.getCode() + "','"  + ModeIDType.FKZJSH.getCode() 
			+ "','"  + ModeIDType.ZSYS.getCode() + "','"  + ModeIDType.CSDCS.getCode() 
			+ "','"  + ModeIDType.ZSES.getCode() + "','"  + ModeIDType.DSCS.getCode() 
			+ "','"  + ModeIDType.DSFS.getCode() + "','"  + ModeIDType.FKJLSH.getCode() + "')");
    	
        int records = otherMessageAppService.countByExt(otherMessageAppExt);
        
        PageVo page = getPage(otherMessageAppExt);
        page.setRecords(records);
        if (records > 0) {
            List<OtherMessageApp> otherMessageApps = otherMessageAppService.selectByExt(otherMessageAppExt);
            if(CollectionUtils.isNotEmpty(otherMessageApps)) {
            	for(int i=0;i<otherMessageApps.size();i++) {
            		OtherMessageApp messageApp = otherMessageApps.get(i);
            		messageApp.setContent(HtmlUtil.filterHtml(messageApp.getContent()));
            	}
            }
            List<OtherMessageAppResponse> otherMessageAppResponses = mapOtherMessageApps(otherMessageApps);
            page.setRows(otherMessageAppResponses);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
	}
	
	/**
	 * 征信反馈收件箱
	 * @param otherMessageAppResquest
	 * @return
	 */
	@ApiOperation(value = "征信反馈收件箱", response = OtherMessageAppResponseItem.class, httpMethod="POST")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
	@RequestMapping("listZxcxResult")
	public ApiResponse listZxcxResult(@Validated @RequestBody OtherMessageAppResquest otherMessageAppResquest) {
		SysUser currentUser = tokenUserHelper.getUser();
    	OtherMessageAppExt otherMessageAppExt = new OtherMessageAppExt();
    	otherMessageAppExt.setBaseWhere();
    	otherMessageAppExt.setSalesmanId(currentUser.getSalersmanId());
//    	查询所有，已查看放后面
    	otherMessageAppExt.setOrderSql("(CASE WHEN `STATUS_MSG` != " + MessageStatus.YI_CHA_KAN.getCode() + " THEN 0 ELSE 1 END), `TIME_CREATE` DESC"); //最新
    	otherMessageAppExt.setPage(otherMessageAppResquest.getPage());
    	otherMessageAppExt.setRows(otherMessageAppResquest.getRows());
//    	不获取mode_id 为这些的信息
    	otherMessageAppExt.setWhereSql(" AND `MODE_ID` IN ('" + ModeIDType.ZXCX.getCode() 
    			+ "','"  + ModeIDType.ZXJG.getCode()  + "','"  + ModeIDType.ZXUG.getCode() + "')");
    	
        int records = otherMessageAppService.countByExt(otherMessageAppExt);
        
        PageVo page = getPage(otherMessageAppExt);
        page.setRecords(records);
        if (records > 0) {
            List<OtherMessageApp> otherMessageApps = otherMessageAppService.selectByExt(otherMessageAppExt);
            if(CollectionUtils.isNotEmpty(otherMessageApps)) {
            	for(int i=0;i<otherMessageApps.size();i++) {
            		OtherMessageApp messageApp = otherMessageApps.get(i);
            		messageApp.setContent(HtmlUtil.filterHtml(messageApp.getContent()));
            	}
            }
            List<OtherMessageAppResponse> otherMessageAppResponses = mapOtherMessageApps(otherMessageApps);
            page.setRows(otherMessageAppResponses);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
	}
	
	 /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键消息警告<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键消息警告", response = OtherMessageAppResponseItem.class, httpMethod="POST")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
    @RequestMapping("getById")
    public ApiResponse getById(@Validated(Id.class) @RequestBody ParentModel parentModel){
       SysUser user = tokenUserHelper.getUser();
       OtherMessageApp otherMessageApp = otherMessageAppService.selectById(parentModel.getId());
       if(null == otherMessageApp) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       otherMessageApp.setStatusMsg(MessageStatus.YI_CHA_KAN.getCode());
       otherMessageApp.setModifier(user.getId());
       otherMessageApp.setModifierName(user.getName());
       otherMessageAppService.saveUpdateAndDelete(otherMessageApp, OperateType.edit);

       
       OtherMessageAppResponseItem mapOtherMessageApp = redisObjectClient.execute(new RedisCallback<OtherMessageAppResponseItem>() {
			@Override
			public OtherMessageAppResponseItem doInRedis(RedisConnection redisConnection)
					throws DataAccessException {
				OtherMessageAppResponseItem mapOtherMessageApp = mapOtherMessageApp(redisConnection, otherMessageApp);
				
				return mapOtherMessageApp;
			}
       });
       return ApiResponse.success(mapOtherMessageApp);
    }
	
	/**
	 * 消息警告
	 * @param otherMessageAppResquest
	 * @return
	 */
	@ApiOperation(value = "消息警告列表", response = OtherMessageAppResponseItem.class, httpMethod="POST")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
	@RequestMapping("list")
	public ApiResponse list(@Validated @RequestBody OtherMessageAppResquest otherMessageAppResquest) {
		SysUser currentUser = tokenUserHelper.getUser();
    	OtherMessageAppExt otherMessageAppExt = new OtherMessageAppExt();
    	otherMessageAppExt.setBaseWhere();
    	otherMessageAppExt.setSalesmanId(currentUser.getSalersmanId());
    	//查询所有，已查看放后面
    	otherMessageAppExt.setOrderSql("(CASE WHEN `STATUS_MSG` != " + MessageStatus.YI_CHA_KAN.getCode() + " THEN 0 ELSE 1 END), `TIME_CREATE` DESC"); //最新
    	otherMessageAppExt.setPage(otherMessageAppResquest.getPage());
    	otherMessageAppExt.setRows(otherMessageAppResquest.getRows());
//    	不获取mode_id 为这些的信息
//    	otherMessageAppExt.setWhereSql(" AND `MODE_ID` NOT IN ('" + ModeIDType.CSDZS.getCode() 
//    			+ "','"  + ModeIDType.FKGPS.getCode() + "','"  + ModeIDType.FKZJSH.getCode() 
//    			+ "','"  + ModeIDType.ZSYS.getCode() + "','"  + ModeIDType.ZXCX.getCode() 
//    			+ "','"  + ModeIDType.ZXJG.getCode() + "','"  + ModeIDType.ZXUG.getCode()
//    			+ "','"  + ModeIDType.CSDCS.getCode() + "','"  + ModeIDType.ZSES.getCode() + "','"  + ModeIDType.DSCS.getCode() 
//    			+ "','"  + ModeIDType.DSFS.getCode() + "','"  + ModeIDType.FKJLSH.getCode() + "')");
    	
        int records = otherMessageAppService.countByExt(otherMessageAppExt);
        
        PageVo page = getPage(otherMessageAppExt);
        page.setRecords(records);
        if (records > 0) {
            List<OtherMessageApp> otherMessageApps = otherMessageAppService.selectByExt(otherMessageAppExt);
            if(CollectionUtils.isNotEmpty(otherMessageApps)) {
            	for(int i=0;i<otherMessageApps.size();i++) {
            		OtherMessageApp messageApp = otherMessageApps.get(i);
            		messageApp.setContent(HtmlUtil.filterHtml(messageApp.getContent()));
            	}
            }
            List<OtherMessageAppResponse> otherMessageAppResponses = mapOtherMessageApps(otherMessageApps);
            page.setRows(otherMessageAppResponses);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
	}
	
	/**
	 * 消息警告统计
	 * @return
	 */
	@ApiOperation(value = "消息警告统计", response = Integer.class, httpMethod="POST")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = SystemConsts.MOBILE_FLAG, defaultValue="ios", value = "请求机器标识", required = true, paramType = "header", dataType = "String"),
    	@ApiImplicitParam(name = SystemConsts.HEADER_FOR_TOKEN, defaultValue="Ajesget8XF7zNMpt+MM8cr0wI8S+IO6a9giEKNouXWvOO3wWWyaKjSDTqRUtHlcNbjCg1JaPdjRX6dX/O1oGLgE=", value = "token", required = true, paramType = "header", dataType = "String")
    })
	@RequestMapping(value="count", method = {RequestMethod.GET,RequestMethod.POST})
	public ApiResponse count() {
		SysUser currentUser = tokenUserHelper.getUser();
    	OtherMessageAppExt otherMessageAppExt = new OtherMessageAppExt();
    	otherMessageAppExt.setBaseWhere();
    	otherMessageAppExt.setSalesmanId(currentUser.getSalersmanId());
    	otherMessageAppExt.setWhereSql("`STATUS_MSG` IN (" + MessageStatus.WEI_TUI_SONG.getCode() + "," + MessageStatus.YI_TUI_SONG.getCode() + ")");
        int records = otherMessageAppService.countByExt(otherMessageAppExt);
        return ApiResponse.success(records);
	}
  
}
